import { NextResponse } from 'next/server'
import { uploadFile, validateFile, ERROR_CODES } from '@/lib/storage'

/**
 * POST /api/upload - 上传文件（所有文件都存储到本地）
 * 支持需求 3.4
 */
export async function POST(request) {
    try {
        const formData = await request.formData()
        const file = formData.get('file')
        const type = formData.get('type') || 'app' // 'app' 或 'thumbnail'

        // 验证文件是否存在
        if (!file || !(file instanceof File)) {
            return NextResponse.json({
                success: false,
                error: {
                    code: ERROR_CODES.VALIDATION_ERROR,
                    message: '请选择要上传的文件'
                }
            }, { status: 400 })
        }

        // 验证文件类型
        if (!['app', 'thumbnail'].includes(type)) {
            return NextResponse.json({
                success: false,
                error: {
                    code: ERROR_CODES.VALIDATION_ERROR,
                    message: '无效的文件类型参数'
                }
            }, { status: 400 })
        }

        // 验证文件
        const validationError = validateFile(file, type)
        if (validationError) {
            return NextResponse.json({
                success: false,
                error: {
                    code: type === 'app' ? ERROR_CODES.INVALID_FILE_TYPE : ERROR_CODES.FILE_TOO_LARGE,
                    message: validationError
                }
            }, { status: 400 })
        }

        // 上传文件
        const uploadResult = await uploadFile(file, type === 'app' ? 'apps' : 'thumbnails')

        if (uploadResult.error) {
            return NextResponse.json({
                success: false,
                error: {
                    code: ERROR_CODES.UPLOAD_FAILED,
                    message: uploadResult.error
                }
            }, { status: 500 })
        }

        return NextResponse.json({
            success: true,
            data: {
                file: {
                    path: uploadResult.path,
                    url: uploadResult.url,
                    name: file.name,
                    size: file.size,
                    type: file.type
                },
                message: '文件上传成功'
            }
        })

    } catch (error) {
        console.error('文件上传失败:', error)

        // 处理特定错误
        if (error.message.includes('File size')) {
            return NextResponse.json({
                success: false,
                error: {
                    code: ERROR_CODES.FILE_TOO_LARGE,
                    message: '文件大小超出限制'
                }
            }, { status: 413 })
        }

        return NextResponse.json({
            success: false,
            error: {
                code: ERROR_CODES.UPLOAD_FAILED,
                message: '文件上传失败',
                details: process.env.NODE_ENV === 'development' ? error.message : undefined
            }
        }, { status: 500 })
    }
}

/**
 * GET /api/upload - 获取上传配置信息
 */
export async function GET() {
    return NextResponse.json({
        success: true,
        data: {
            config: {
                maxFileSize: {
                    app: 100 * 1024 * 1024, // 100MB
                    thumbnail: 5 * 1024 * 1024 // 5MB
                },
                allowedTypes: {
                    app: [
                        'application/x-msdownload',
                        'application/octet-stream',
                        'application/zip',
                        'application/x-zip-compressed'
                    ],
                    thumbnail: [
                        'image/jpeg',
                        'image/png',
                        'image/webp',
                        'image/gif'
                    ]
                }
            }
        }
    })
}